package com.example.i2v.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/upload")
@CrossOrigin(origins = "*")
public class FileUploadController {

    /**
     * 上传图片并转换为Base64
     */
    @PostMapping("/image")
    public ResponseEntity<Map<String, Object>> uploadImage(@RequestParam("file") MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                result.put("success", false);
                result.put("message", "上传的文件为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            // 检查文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                result.put("success", false);
                result.put("message", "只支持图片文件上传");
                return ResponseEntity.badRequest().body(result);
            }
            
            // 检查文件大小（20MB限制）
            if (file.getSize() > 20 * 1024 * 1024) {
                result.put("success", false);
                result.put("message", "文件大小不能超过20MB");
                return ResponseEntity.badRequest().body(result);
            }
            
            // 检查支持的图片格式
            String[] supportedTypes = {"image/jpeg", "image/jpg", "image/png", "image/bmp", "image/webp"};
            boolean isSupported = false;
            for (String type : supportedTypes) {
                if (type.equals(contentType)) {
                    isSupported = true;
                    break;
                }
            }
            
            if (!isSupported) {
                result.put("success", false);
                result.put("message", "支持的图片格式：JPEG、JPG、PNG、BMP、WEBP");
                return ResponseEntity.badRequest().body(result);
            }
            
            // 转换为Base64
            byte[] fileBytes = file.getBytes();
            String base64String = Base64.getEncoder().encodeToString(fileBytes);
            String dataUrl = "data:" + contentType + ";base64," + base64String;
            
            log.info("图片上传成功，文件名: {}, 大小: {} bytes, 类型: {}", 
                    file.getOriginalFilename(), file.getSize(), contentType);
            
            result.put("success", true);
            result.put("message", "图片上传成功");
            result.put("filename", file.getOriginalFilename());
            result.put("size", file.getSize());
            result.put("contentType", contentType);
            result.put("base64", dataUrl);
            result.put("timestamp", System.currentTimeMillis());
            
            return ResponseEntity.ok(result);
            
        } catch (IOException e) {
            log.error("文件上传失败", e);
            result.put("success", false);
            result.put("message", "文件上传失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
    
    /**
     * 获取支持的文件格式信息
     */
    @GetMapping("/info")
    public ResponseEntity<Map<String, Object>> getUploadInfo() {
        Map<String, Object> result = new HashMap<>();
        
        result.put("maxFileSize", "10MB");
        result.put("supportedFormats", new String[]{"JPEG", "JPG", "PNG", "BMP", "WEBP"});
        result.put("supportedMimeTypes", new String[]{
            "image/jpeg", "image/jpg", "image/png", "image/bmp", "image/webp"
        });
        result.put("imageRequirements", Map.of(
            "分辨率范围", "[360, 2000]像素",
            "文件大小", "不超过10MB",
            "透明通道", "PNG透明通道不支持"
        ));
        
        return ResponseEntity.ok(result);
    }
}